import React, { useEffect, useState } from 'react';
import { Row, Col, Icon, Input, Form, Menu, message, Badge } from 'antd';
import AxCard from '@/components/AxBase/AxCard';
import './style.css';
import { AxButton } from '@/components/AxBase';
import StandardFormRow from './components/StandardFormRow';
import TagSelect from './components/TagSelect';
import IconFont from '@/assets/iconfont';
import { router } from 'umi';
import { AxTable } from '@/components/AxList';
import { axconst } from '@/shared/axconst';
import {
  AxEditableContext,
  AxEditableForm,
  AxEditableSimple,
} from '@/components/AxForm/AxFormItem';
import { axhttp } from '@/utils/axhttp';
import { axhelper } from '@/shared/axhelper';

const FormItem = Form.Item;
const { Search } = Input;
const { getListXhr, postFormXhr } = axhttp;
const Purchase: React.FC<any> = props => {
  const [selectedKeys, setSelectedKeys] = useState<any>(['all']);
  const [loading, setLoading] = useState(false);
  const [count, setCount] = useState(0);
  const [data, setData] = useState(axconst.initialList);
  const [brand, setBrand] = useState([]);
  const [character, setCharacter] = useState([]);
  const [controllLevel, setControllLevel] = useState([]);
  /** 排序标签 */
  const [sortAll, setSortAll] = useState('asc');
  const [sortNum, setSortNum] = useState('asc');
  const [sortPrice, setSortPrice] = useState('asc');
  /** Tag标签 */
  const [brandTag, setBrandTag] = useState([]);
  const [characterTag, setCharacterTag] = useState([]);
  const [controllLevelTag, setControllLevelTag] = useState([]);
  /** 当前排序状态 */
  const [sort, setSort] = useState({});
  const [search, setSearch] = useState({});
  const user = axhelper.getUserInfo();

  useEffect(() => {
    handleReadCartSum();
    handleReadGoods();
  }, []);

  /** 获取商品列表 */
  const handleReadGoods = (p: any = {}) => {
    let params = {
      ...sort,
      ...search,
      ...p,
    };
    setLoading(true);
    getListXhr('/api/goods/read', params)
      .then((res: any) => {
        setData(res);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  /** 获取购物车中商品总数量 */
  const handleReadCartSum = () => {
    getListXhr('/api/cart/read').then((res: any) => {
      let c = 0;
      c = res.list.reduce((pre: any, cur: any) => pre + parseInt(cur.amount), 0);
      setCount(c);
    });
  };

  /** 综合排序 */
  const handleChangeOrderAll = (e: any) => {
    const sort = sortAll === 'asc' ? 'desc' : 'asc';
    const sortVal = { sort: 'all ' + sort };
    setSortAll(sort);
    setSort(sortVal);
    handleReadGoods(sortVal);
    handleChangeOrder(e);
  };

  /**销量排序 */
  const handleChangeOrderNum = (e: any) => {
    const sort = sortNum === 'asc' ? 'desc' : 'asc';
    const sortVal = { sort: 'number  ' + sort };
    setSortNum(sort);
    setSort(sortVal);
    handleReadGoods(sortVal);
    handleChangeOrder(e);
  };

  /** 价格排序 */
  const handleChangeOrderPrice = (e: any) => {
    const sort = sortPrice === 'asc' ? 'desc' : 'asc';
    const sortVal = { sort: 'price ' + sort };
    setSortPrice(sort);
    setSort(sortVal);
    handleReadGoods(sortVal);
    handleChangeOrder(e);
  };

  /** 排序 */
  const handleChangeOrder = (e: any) => {
    e && e.preventDefault();

    e.currentTarget.parentNode.childNodes.forEach((i: any) => (i.className = 'ax-purchase-order'));
    e.currentTarget.className = 'ax-purchase-order ax-purchase-order-selected';
  };

  /** 加入收藏 */
  const handleInterest = (productId: any) => {
    postFormXhr('/api/favorite/create', { productId, userId: user.id }).then((res: any) => {
      message.success('收藏成功');
    });
  };

  /** 加入购物车 */
  const handleAddCart = (e: any, form: any, product: any) => {
    form.validateFields((error: any, values: any) => {
      if (error && error[e.currentTarget.id]) {
        return;
      }

      getListXhr('/api/cart/read', {
        id: product.id,
      }).then((res: any) => {
        /** 如果存在，修改数量 */
        if (res && res.list && res.list.length > 0) {
          const p = res.list[0];
          postFormXhr('/api/cart/update', {
            ...p,
            amount: parseInt(p.amount) + parseInt(values.count),
          }).then(() => {
            handleReadCartSum();
            message.success('加入购物车成功');
          });
        } else {
          /** 如果不存在，添加到购物车中 */
          postFormXhr('/api/cart/create', {
            ...product,
            amount: values.count,
          }).then(() => {
            handleReadCartSum();
            message.success('加入购物车成功');
          });
        }
      });
    });
  };

  /** 商品品牌过滤 */
  const handleChangeBrand = (v: any) => {
    setBrandTag(v);
    const s = {
      brand: v,
    };
    setSearch({
      ...search,
      ...s,
    });
    handleReadGoods(s);
  };

  const columns = [
    {
      dataIndex: 'image',
      width: 110,
      render: (val: any) => {
        return (
          <img
            src={(val && val !== '' && val) || '/img/nopic.jpg'}
            style={{ height: 110, width: 110 }}
          />
        );
      },
    },
    {
      width: axconst.width.longx,
      render: (val: any, record: any) => {
        return (
          <div style={{ marginLeft: 16 }}>
            <h4 className="ant-list-item-meta-title">{record.name}</h4>
            {/* <div className="ant-list-item-meta-description">{record.eName}</div> */}
            <div onClick={() => handleInterest(record.id)}>
              <span className="ax-interest">
                <Icon type="heart" />
                收藏
              </span>
            </div>
          </div>
        );
      },
    },
    {
      width: axconst.width.long,
      render: (val: any, record: any) => {
        return (
          <div>
            <div>
              <span>产品规格：{record.productSpec}</span>
            </div>
            <div>
              <span>别名：{record.alias}</span>
            </div>
          </div>
        );
      },
    },
    {
      width: axconst.width.long,
      render: (val: any, record: any) => {
        return (
          <div>
            <div>
              <p>单价：<span style={{color:'#f96712'}}>￥{record.price}</span></p>
            </div>
            <div>
              <p>库存：<span style={{color:'blue'}}>{record.stock}</span></p>
            </div>
          </div>
        );
      },
    },
    {
      width: axconst.width.long,
      render: (val: any, record: any) => {
        return (
          <div>
            <div>
              <span>销量：{record.saleAmount}</span>
            </div>
            <div>
              <span>品类名称：{record.categoryName}</span>
            </div>
          </div>
        );
      },
    },
    {
      width: 140,
      render: (val: any, record: any) => {
        return (
          <AxEditableForm>
            <AxEditableSimple
              style={{ width: 124 }}
              precision={0}
              step={1}
              min={1}
              cellType="number"
              editing={true}
              record={{ count: 1 }}
              dataIndex="count"
            />
            <AxEditableContext.Consumer>
              {form => {
                return (
                  <AxButton
                    className="ax-no-class"
                    style={{ marginTop: 6 }}
                    ghost
                    onClick={(e: any) => handleAddCart(e, form, record)}
                  >
                    <Icon type="shopping-cart" />
                    加入购物车
                  </AxButton>
                );
              }}
            </AxEditableContext.Consumer>
          </AxEditableForm>
        );
      },
    },
  ];

  const handleChangePage = ({ current, pageSize }: any) => {
    handleReadGoods({ currentPage: current, pageSize });
  };

  return (
    <>
      <AxCard
        style={{ marginBottom: '15px', height: '100%', width: '72%', margin: '24px auto' }}
        bodyStyle={{ padding: 0 }}
      >
        <Row>
          <Col span={6}>
            {/* <img src='/img/logo.png' style={{ backgroundColor: '#1ca9e6' }} /> */}
          </Col>
          <Col span={12}>
            <Search
              placeholder="请输入商品名称搜索"
              onSearch={(val: any) => handleReadGoods({ name: val })}
              allowClear
            />
          </Col>
          <Col span={6}>
            <Badge count={count} overflowCount={100}>
              <AxButton
                className="ax-no-class"
                style={{ marginLeft: 30 }}
                ghost
                onClick={() => router.push('/buyer/material/cart/data')}
              >
                我的购物车
                <Icon type="shopping-cart" />
              </AxButton>
            </Badge>
          </Col>
        </Row>
      </AxCard>
      <div style={{ borderBottom: '2px solid #409eff' }}>
        <AxCard
          style={{ marginBottom: 15, height: '100%', width: '72%', margin: '0 auto' }}
          bodyStyle={{ padding: 0 }}
        >
          <Menu
            theme="light"
            mode="horizontal"
            selectedKeys={selectedKeys}
            // style={{ lineHeight: `${axconst.header.height - 2}px`, float: 'right', backgroundColor: '#409eff' }}
            onClick={({ key }) => setSelectedKeys([key])}
          >
            <Menu.Item key="all" onClick={() => router.push('/material/goods/data')}>
              <Icon type="unordered-list" />
              全部商品
            </Menu.Item>
          </Menu>
        </AxCard>
      </div>
      <AxCard
        style={{
          marginBottom: 15,
          height: '100%',
          width: '72%',
          margin: '0 auto',
          borderTop: '1px solid #e8e8e8',
          borderBottom: '1px solid #e8e8e8',
        }}
        bodyStyle={{ padding: '6px 0px' }}
      >
        <a className="ax-purchase-order ax-purchase-order-selected" onClick={handleChangeOrderAll}>
          <>
            综合
            <IconFont type={'icon' + sortAll} />
          </>
        </a>
        <a className="ax-purchase-order" onClick={handleChangeOrderNum}>
          销量
          <IconFont type={'icon' + sortNum} />
        </a>
        <a className="ax-purchase-order" onClick={handleChangeOrderPrice}>
          价格
          <IconFont type={'icon' + sortPrice} />
        </a>
      </AxCard>
      <AxCard
        style={{ marginBottom: '15px', height: '100%', width: '72%', margin: '24px auto' }}
        bodyStyle={{ paddingLeft: 0, paddingRight: 0, paddingTop: 0 }}
      >
        <AxTable
          size="default"
          bordered={false}
          showHeader={false}
          checkboxModel={false}
          columns={columns}
          data={data}
          loading={loading}
          onChange={handleChangePage}
        />
      </AxCard>
    </>
  );
};

export default Purchase;
